﻿using Rsd.Dudu;
using Rsd.Dudu.BizModel;
using Rsd.Dudu.Core;
using Rsd.Dudu.Helpers;
using Rsd.Dudu.Web;
using Rsd.Dudu.Web.Core;
using Rsd.Dudu.Web.MVC;
using Rsd.Faith.Core;
using Rsd.Faith.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Rsd.Faith.Web.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class BizController:Rsd.Faith.Core.FaithController
    {
        /// <summary>
        /// json 结构:
        /// {
        /// modelType:'Rsd.xxx.xxx',
        /// record:{name:'',age:20}
        /// }
        /// </summary>
        [PramaRule("modelType", "类型名(modelType)")]
        [PramaRule("record", "保存对象(record)", typeof(JsonObject))]
        [ApiService("保存数据")]
        public object Save()
        {
            Rsd.Faith.Core.ModelBase obj = null;
            string modelType = base["modelType"].ToString();
            var target = MyType.GetType(modelType);
            var _json = base.Context.Request.GetPrama("record").ConvertTo<JsonObject>();

            if (target == null)
            {
                return new ErrorResult<ErrorCodesType>(ErrorCodesType.W0003,modelType);
            }
            
            try
            {
                if (string.IsNullOrEmpty(_json.Get<string>("Creator")))
                {
                    _json.Add("Creator", this.GetCurrentUserId());
                }
                if (string.IsNullOrEmpty(_json.Get<string>("Modifier")))
                {
                    _json.Add("Modifier", this.GetCurrentUserId());
                }
                
                obj = this.SaveObject(target.Owner, _json,string.IsNullOrEmpty( _json.Get<string>("Id"))? ObjectStateType.New: ObjectStateType.Update );
            }
            catch (System.Exception ex)
            {
                ErrorCodesType.W0005.SubmitError(modelType, ex.ToString());
            }

            return JsonHelper.ConvertToJsonObject(obj);
        }
        /// <summary>
        /// 
        /// </summary>
        [PramaRule("modelType", "类型名(modelType)")]
        [PramaRule("key", "对象主键(key)", typeof(JsonObject))]
        [ApiService("删除数据")]
        public object Delete()
        {
            //业务处理
            string modelType = base["modelType"].ToString();
            var target = MyType.GetType(modelType);
            var key = base["key"].ToString();

            if (target == null)
            {
                return new ErrorResult<ErrorCodesType>(ErrorCodesType.W0003,modelType);
            }
            try
            {
                this.DeleteObject(target.Owner, key, DeleteType.Logic);
            }
            catch (System.Exception ex)
            {
                ErrorCodesType.W0006.SubmitError(modelType, ex.ToString());

            }

            return new { };

        }


        [PramaRule("modeltype", "对象类型(modeltype)")]
        [PramaRule("id", "键值(id)")]
        [ApiService("获取对象")]
        public object GetObject()
        {
            string modelType = this["modelType"].ToString();
            var t = MyType.GetType(modelType);


            if (t == null)
            {
                return new ErrorResult<ErrorCodesType>(ErrorCodesType.W0003, modelType);
              
            }
            string key = this["id"].ToString();
            return this.GetObject(t.Owner, key);
        }
        /// <summary>
        /// 
        /// </summary>
        [PramaRule("modeltype", "modeltype")]
        [PramaRule("pagesize", "pagesize", 0, 10000, false)]
        [PramaRule("pageindex", "pageindex", 0, 10000, false)]
        [PramaRule("where", "where", typeof(JsonObject[]), false)]
        [PramaRule("sort", "sort", typeof(JsonObject[]), false)]
        [PramaRule("suffix", "suffix", typeof(string), false)]
        [ApiService("获取列表数据")]
        public object GetList()
        {
            int pageSize = 1000;
            int pageIndex = 0;

            string modelType = base["modelType"].ToString();
            var _temp = base["pagesize"];
            if (_temp.Exist)
            {
                int.TryParse(_temp.ToString(), out pageSize);
            }

            _temp = base["pageindex"];
            if (_temp.Exist)
            {
                int.TryParse(_temp.ToString(), out pageIndex);
            }

            JsonObject _rs = null;
            IMyType t = null;

            t = MyType.GetType(modelType);

            if (t == null)
            {
                return new ErrorResult<ErrorCodesType>(ErrorCodesType.W0003, modelType);
            }
            var _tableNameSuffix = "";
            JsonObject[] where = base.Context.Request.GetPrama("where").ConvertTo< JsonObject[]>();
            JsonObject[] sort = base.Context.Request.GetPrama("sort").ConvertTo<JsonObject[]>();

            var whereConditions = JsonHelper.GetWhereConditions(t, where);
            var sortConditions = JsonHelper.GetOrderConditions(t, sort);
            var ts = t.GetTableSchema();

            if (ts.TablePartitioner != null)
            { 
                if (this["suffix"].Exist)
                {
                    _tableNameSuffix = this["suffix"].ToString();
                }

                if (string.IsNullOrEmpty(_tableNameSuffix))
                {
                    return new ErrorResult<ErrorCodesType>(ErrorCodesType.W0004, "suffix", modelType);
                }
            }

            _rs = this.GetPaggingJson(t, pageIndex, pageSize, whereConditions, sortConditions, _tableNameSuffix);
            return _rs;
        }
    }
}